package com.nclg.exam.controller;

import com.github.pagehelper.PageInfo;
import com.nclg.exam.dto.InsertPaperDto;
import com.nclg.exam.dto.PaperDto;
import com.nclg.exam.dto.UpdatePaperDto;
import com.nclg.exam.dto.PaperListDto;
import com.nclg.exam.entity.LayResponse;
import com.nclg.exam.service.PaperService;
import com.nclg.exam.utils.DateUtils;
import com.nclg.exam.utils.JsonResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Date;

@RestController
@RequestMapping("/paper")
public class PaperController {

    @Autowired
    private PaperService paperService;

    /**
     * 查询试卷
     * @param dto
     * @return
     */
    @GetMapping("/selectPaperByPage")
    public JsonResult selectPaperByPage(PaperDto dto){
        PageInfo<PaperListDto> list = paperService.selectByPage(dto);
        LayResponse<PaperListDto> layResponse = new LayResponse<>("0", "", list.getTotal(), list.getList());
        return JsonResult.success(layResponse);
    }

    /**
     * 修改试卷状态
     * @param pstatus
     * @param pid
     * @return
     */
    @PutMapping("/updatePaperStatus/{pstatus}/{pid}")
    public JsonResult updatePaperStatus(@PathVariable String pstatus, @PathVariable String pid){
        Boolean isTrue = paperService.updatePaperStatus(pstatus, Long.valueOf(pid));
        if (!isTrue) return JsonResult.failure("修改失败");
        return JsonResult.success();
    }

    /**
     * 编辑试卷考试时间
     * @param dto
     * @return
     */
    @PutMapping("/updatePaper")
    public JsonResult updatePaper(UpdatePaperDto dto){
        Date pEndtime = DateUtils.addHours(DateUtils.format(dto.getPBegintime()), dto.getPDuration());
        dto.setPEndtime(pEndtime);
        Boolean isTrue = paperService.updatePaper(dto);
        if (!isTrue) return JsonResult.failure("修改失败");
        return JsonResult.success("修改成功");
    }

    /**
     * 查询该类型题目总数量
     * @param type
     * @return
     */
    @GetMapping("/selectQuestionCount/{type}")
    public JsonResult selectQuestionCount(@PathVariable String type){
        int count = paperService.selectQuestionCount(type);
        return JsonResult.success(count);
    }

    /**
     * 创建试卷
     * @param dto
     * @return
     */
    @PostMapping("/insertPaper")
    public JsonResult insertPaper(InsertPaperDto dto){
        Date pEndtime = DateUtils.addHours(DateUtils.format(dto.getPBegintime()), dto.getPDuration());
        dto.setPEndtime(pEndtime);
        boolean isTrue = paperService.insertPaper(dto);
        if (!isTrue) return JsonResult.failure("创建失败");
        return JsonResult.success("创建成功");
    }
}
